package com.ganmiao.utils;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.util.*;

@Slf4j
public class SignV2Util {

    private static final String SIGN = "sign";

    /**
     * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public static String createMD5Sign(Map<String, Object> paramMap, String appKey) {
        StringBuilder sb = new StringBuilder();
        try {
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            List<Map.Entry<String, Object>> sortedParamList = new ArrayList<Map.Entry<String, Object>>(paramMap.entrySet());
            sortedParamList.sort(new Comparator<Map.Entry<String, Object>>() {
                @Override
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).compareTo(o2.getKey());
                }
            });

            for (Map.Entry<String, Object> item : sortedParamList) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (Objects.nonNull(val) && !SIGN.equals(key)) {
                        val = URLEncoder.encode(val.toString(), "utf-8");
                        sb.append(key).append("=").append(val).append("&");
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }

        sb.append("appKey=").append(appKey);
        String sign = SecureUtil.md5(sb.toString()).toUpperCase();
        log.info("param={},sign={}", sb.toString(), sign);

        return sign;
    }

    /**
     * 校验md5签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
     */
    public static Boolean checkMD5Sign(Map<String, Object> paramMap, String appKey, String sign) {
        StringBuilder sb = new StringBuilder();
        try {
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            List<Map.Entry<String, Object>> sortedParamList = new ArrayList<Map.Entry<String, Object>>(paramMap.entrySet());
            sortedParamList.sort(new Comparator<Map.Entry<String, Object>>() {
                @Override
                public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                    return (o1.getKey()).compareTo(o2.getKey());
                }
            });

            for (Map.Entry<String, Object> item : sortedParamList) {
                if (StringUtils.isNotBlank(item.getKey())) {
                    String key = item.getKey();
                    Object val = item.getValue();
                    if (null != val && !"".equals(val) && !SIGN.equals(key)) {
                        val = URLEncoder.encode(val.toString(), "utf-8");
                        sb.append(key).append("=").append(val).append("&");
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        sb.append("appKey=").append(appKey);
        String newSign = SecureUtil.md5(sb.toString()).toUpperCase();
        log.info("param: {},newSign={},sign={}", sb.toString(), newSign, sign);
        if (!newSign.equals(sign)) {
            log.error("newSign not equals sign !");
            return false;
        }

        return true;
    }

    /***
     * 生成微信sha1方法签名
     **/
    public static String encryptSha1(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static void main(String[] args) {

        JSONObject reqObj = new JSONObject();
        reqObj.put("amount", "300.00");
        reqObj.put("guarantee_code", "GSDZTJ202405220010");
        reqObj.put("request_no", "611f0e54-b82d-4dc7-b516-25acdedcd177");
        reqObj.put("guarantee_type", "1");
        reqObj.put("status", "0");
        reqObj.put("url", "123");
        //使用验签工具生成进行生成sign
        String sign = SignV2Util.createMD5Sign(reqObj, "eicp");
        System.out.println("sign=" +sign);

        Boolean result = checkMD5Sign(reqObj, "eicp", sign);
        System.out.println(result);
    }

}
